<script setup>
import '@wangeditor/editor/dist/css/style.css'
import {onBeforeUnmount, onMounted, reactive, ref, shallowRef} from 'vue'
import {Editor, Toolbar} from '@wangeditor/editor-for-vue'
import {
  addArticleService,
  deleteArticleBatchService,
  deleteArticleService,
  getArticleListService,
  getCategoryNameService,
  updateArticleService,
} from '../api/article.js'
import {ElMessage, ElMessageBox} from "element-plus";
import {Plus} from "@element-plus/icons-vue";

// 数据模型
const data = reactive({
  token: JSON.parse(localStorage.getItem('user')).token,
  title: '',
  pageNum: 1,
  pageSize: 5,
  tableData: [],
  categoryList: [],
  total: 0,
  dialogVisible: false,
  dialogTitle: '',
  htmlDialogVisible: false,
  articleForm: {},
  coverUrl: '',
  rules: {
    title: [
      {required: true, message: '请输入标题', trigger: 'blur'},
      {min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur'}
    ],
    content: [
      {required: true, message: '请输入内容', trigger: 'blur'},
    ],
    publishTime: [
      {required: true, message: '请选择发布时间', trigger: 'blur'},
    ],
    categoryId: [
      {required: true, message: '请选择分类', trigger: 'blur'},
    ],
  },
  selectedRows: [],
  html: ''
})

const formRef = ref()

// 初始化
const editorRef = shallowRef()
const mode = 'default'
const editorConfig = {MENU_CONF: {}}

// 图片上传配置
editorConfig.MENU_CONF['uploadImage'] = {
  headers: {
    Authorization: data.token
  },
  server: 'http://127.0.0.1:9090/api/file/wang/upload',
  fieldName: 'file',
}

// 销毁组件
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

// 记录实例
const handleCreated = (editor) => {
  editorRef.value = editor
}

// 获取文章分页列表
const ArticleList = async () => {
  let params = {
    pageNum: data.pageNum,
    pageSize: data.pageSize,
    title: data.title,
  }
  const res = await getArticleListService(params);
  if (res.data.code === '200') {
    data.tableData = res.data.data.list
    data.total = res.data.data.total
  } else {
    ElMessage.error(res.data.message)
  }
}

// 页面加载时执行
onMounted(async () => {
  await ArticleList()
})

// 重置
const refresh = async () => {
  data.title = ''
  await ArticleList()
}

// 显示弹窗（新增）
const showAddDialog = () => {
  data.articleForm = {
    id: '',
    cover: '',
    title: '',
    content: '',
    publishTime: null,
    categoryId: '',
    userId: JSON.parse(localStorage.getItem('user')).id
  }
  getCategoryNameService().then(res => {
    data.categoryList = res.data.data
  })
  data.coverUrl = ''
  data.dialogTitle = '新增文章'
  data.dialogVisible = true
}

// 表格行数据
const handleSelectionChange = (val) => {
  data.selectedRows = val
}

// 分页 - pageSize 改变时
const handleSizeChange = (newSize) => {
  data.pageSize = newSize;
  ArticleList();
};

// 分页 - pageNum 改变时
const handleCurrentChange = (newPage) => {
  data.pageNum = newPage;
  ArticleList();
};

// 显示弹窗（修改）
const showUpdateDialog = (row) => {
  getCategoryNameService().then(res => {
    data.categoryList = res.data.data
  })
  data.articleForm = {
    id: row.id,
    cover: row.cover,
    title: row.title,
    content: row.content,
    publishTime: row.publishTime,
    categoryId: row.categoryId,
    userId: ''
  }
  data.coverUrl = row.cover
  data.dialogTitle = '修改文章'
  data.dialogVisible = true
}

// 显示弹窗（富文本编辑器）
const showHtmlDialog = (row) => {
  data.dialogTitle = '文章内容'
  data.htmlDialogVisible = true
  data.html = row.content
}

// 保存文章
const handleSaveArticle = async () => {

  const valid = formRef.value.validate().catch(() => false)

  if (valid) {
    if (data.articleForm.cover) {
      if (data.articleForm.id) {
        const res = await updateArticleService(data.articleForm);
        if (res.data.code === '200') {
          ElMessage.success('修改成功');
          data.dialogVisible = false
          await ArticleList()
        }
      } else {
        const res = await addArticleService(data.articleForm);
        if (res.data.code === '200') {
          ElMessage.success("新增成功")
          data.dialogVisible = false
          await ArticleList()
        }
      }
    } else {
      ElMessage.error("请上传封面")
    }
  } else {
    ElMessage.error("请填写完整信息")
  }
}

// 文章删除
const handleArticleDelete = async (id) => {
  ElMessageBox.confirm(
      '当前操作将永久删除当前用户，是否继续?',
      '警告',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }
  ).then(async () => {
    const res = await deleteArticleService(id)
    if (res.data.code === "200") {
      ElMessage.success("删除成功")
      await ArticleList()
    } else {
      ElMessage.error(res.data.message)
    }
  }).catch(() => {
    ElMessage.info('取消删除')
  })
}

// 文章批量删除
const handleArticleDeleteBatch = async () => {
  if (!data.selectedRows || data.selectedRows.length === 0) {
    ElMessage.warning("请先选择要删除的文章");
    return;
  }
  const ids = data.selectedRows.map(item => item.id)
  ElMessageBox.confirm(
      '当前操作将永久删除选中的文章，是否继续?',
      '警告',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }
  ).then(async () => {
    const res = await deleteArticleBatchService(ids)
    if (res.data.code === "200") {
      ElMessage.success("删除成功");
      await ArticleList();
    } else {
      ElMessage.error(res.data.message);
    }
  }).catch(() => {
    ArticleList()
    ElMessage.info('取消删除');
  });
}

// 头像上传前检查
const beforeAvatarUpload = (file) => {
  const isValidFormat = /\.(jpg|jpeg|png)$/i.test(file.name);
  const isValidSize = file.size / 1024 / 1024 < 2; // 小于 2MB
  if (!isValidFormat) {
    ElMessage.error('只能上传 JPG/JPEG/PNG 格式的图片');
    return false;
  }
  if (!isValidSize) {
    ElMessage.error('图片大小不能超过 2MB');
    return false;
  }
  return true;
};

// 上传头像成功回调
const handleAvatarSuccess = (response) => {
  if (response.code === "200") {
    ElMessage.success("上传成功");
    data.articleForm.cover = response.data;
    data.coverUrl = response.data;
    ArticleList();
  } else {
    ElMessage.error(response.message);
  }
};

// 格式化时间
const formatDate = (dateString) => {
  const date = new Date(dateString);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}年${month}月${day}日 ${hours}:${minutes}:${seconds}`;
};

</script>

<template>
  <el-card>
    <!-- 搜索区域 -->
    <div>
      <el-input v-model="data.title" clearable style="width: 240px" placeholder="请输入文章标题"/>
      <el-button type="primary" style="margin-left: 20px" icon="Search" @click="ArticleList">查询</el-button>
      <el-button type="warning" icon="refresh" @click="refresh">重置</el-button>
    </div>

    <!-- 按钮区域 -->
    <div class="button-container">
      <el-button type="primary" icon="DocumentAdd" @click="showAddDialog">新增文章</el-button>
      <el-button type="danger" style="margin-left: 0" icon="Delete" @click="handleArticleDeleteBatch">批量删除
      </el-button>
    </div>

    <!-- 表格区域 -->
    <div class="table">
      <el-table :data="data.tableData" @selection-change="handleSelectionChange" border
                :row-style="() => ({ height : '58px'})" style="width: 100%;">
        <el-table-column type="selection" align="center" width="55"/>
        <el-table-column prop="cover" align="center" label="封面" width="100">
          <template #default="scope">
            <el-image v-if="scope.row.cover" :src="scope.row.cover" fit="cover"
                      :preview-src-list="[scope.row.cover]" :preview-teleported="true"
                      style="width: 50px; height: 50px; border-radius: 50%">
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="title" align="center" label="标题"/>
        <el-table-column align="center" prop="内容" label="内容">
          <template #default="scope">
            <el-button type="info" icon="Document" @click="showHtmlDialog(scope.row)">显示内容</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="categoryName" align="center" label="文章分类">
          <template #default="scope">
            <el-text type="primary">{{ scope.row.categoryName }}</el-text>
          </template>
        </el-table-column>
        <el-table-column align="center" label="发布时间" width="200">
          <template #default="scope">
            <el-text type="info">{{ formatDate(scope.row.publishTime) }}</el-text>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="200">
          <template #default="scope">
            <el-button type="primary" @click="showUpdateDialog(scope.row)" icon="Edit">修改</el-button>
            <el-button type="danger" icon="Delete" @click="handleArticleDelete(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页区域 -->
    <div class="page">
      <el-pagination
          v-model:current-page="data.pageNum"
          v-model:page-size="data.pageSize"
          :page-sizes="[5, 10, 15, 20]"
          layout="prev, pager, next, jumper, sizes"
          :total="data.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>
  </el-card>

  <el-dialog v-model="data.dialogVisible" :title="data.dialogTitle" align-center width="50%" destroy-on-close>
    <el-form :model="data.articleForm" :rules="data.rules" ref="formRef" label-width="80px"
             style="padding: 0 100px 0 60px">
      <el-form-item class="el-form-item-avatar">
        <el-upload
            class="avatar-uploader"
            action="http://127.0.0.1:9090/api/file/upload"
            :show-file-list="false"
            :headers="{ Authorization: data.token }"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
        >
          <div class="upload-content">
            <img v-if="data.coverUrl" :src="data.coverUrl" alt="" class="avatar"/>
            <el-icon v-else class="avatar-uploader-icon">
              <Plus/>
            </el-icon>
          </div>
        </el-upload>
      </el-form-item>
      <el-form-item label="文章标题" prop="title">
        <el-input v-model="data.articleForm.title" placeholder="请输入标题"/>
      </el-form-item>
      <el-form-item label="文章分类" prop="categoryId">
        <el-select filterable v-model="data.articleForm.categoryId" placeholder="请选择分类" style="width: 100%">
          <el-option
              v-for="category in data.categoryList"
              :key="category.id"
              :label="category.categoryName"
              :value="category.id"
          />
        </el-select>
      </el-form-item>
      <!-- 发布时间 -->
      <el-form-item label="发布时间" prop="publishTime">
        <el-date-picker
            v-model="data.articleForm.publishTime"
            type="datetime"
            placeholder="发布时间"
            format="YYYY年MM月DD日 HH:mm:ss"
            value-format="YYYY-MM-DDTHH:mm:ss" style="width: 100%;"
        />
      </el-form-item>
      <el-form-item label="文章内容" prop="content">
        <div style="border: 1px solid #ccc; width: 100%">
          <Toolbar
              style="border-bottom: 1px solid #ccc"
              :editor="editorRef"
              :mode="mode"
          />
          <Editor
              style="height: 400px; overflow-y: hidden;"
              v-model="data.articleForm.content"
              :mode="mode"
              :defaultConfig="editorConfig"
              @onCreated="handleCreated"
          />
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="data.dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveArticle">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>

  <el-dialog v-model="data.htmlDialogVisible"  :title="data.dialogTitle" align-center
             width="50%" destroy-on-close>
    <div style="padding: 0 60px 0 60px" v-html="data.html"></div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="data.htmlDialogVisible = false">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
:deep(.avatar-uploader .el-upload) {
  width: 150px;
  height: 150px;
  border: 2px dashed var(--el-border-color);
  cursor: pointer;
  display: flex;
  border-radius: 20px;
  align-items: center;
  justify-content: center;
  position: relative;
  left: 240px;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
  margin: 0 auto;
}

:deep(.avatar-uploader .el-upload:hover) {
  border-color: var(--el-color-primary);
}

:deep(.avatar-uploader-icon) {
  font-size: 28px;
  color: #8c939d;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  padding: 5px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
}

.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.button {
  margin-top: 20px;
}

.table {
  margin-top: 20px;
}

.page {
  margin-top: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: center;
}

.button-container {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-top: 20px;
}

:deep() .el-form-item {
  margin-top: 25px;
}
</style>